const redis=require('redis')



const client=redis.createClient(6379,'localhost')




function get(key) {

    //redisClient.select()

    const promise = new Promise((resolve, reject) => {
        client.get(key, (err, val) => {
            if (err) {
                reject(err)
                return            }
            if (val == null) {
                resolve(null)
                return
            }

            try {
                const jobj=JSON.parse(val)
                resolve(jobj)
            } catch (ex) {
                resolve(val)
            }
        })
    })  
    return promise
}

async function getTodoList(){

    const key="todolist"

    const result =await get(key)   //string   

    if(result){
        return result
    }else{
        return []  //读数据库，再把数据库里得到的数据存进缓存
    }
    //从缓存里面获取？？
}


async function addItem(data){

   const tlist= await getTodoList()

    tlist.push(data)

    const jstr=JSON.stringify(tlist)
    const key="todolist"
    client.set(key,jstr)
}


module.exports = {
    getTodoList,addItem
}